<template>
	<view class="container">
		<!-- 水印 -->
		<water-mask></water-mask>
		<!-- <zmm-watermark :watermark="watermark"></zmm-watermark> -->
		<!-- 背景颜色 -->
		<view style="background-color: #FFFFFF;">

			<view class="flex-content">
				<view class="end-title">
					<view v-for="(item,index) in categoryList" :key="index" :class="{btna:countNum == index}"
						@tap="changeMenu(index)">
						{{item.name}}
					</view>
				</view>
				<view class="end-cont">
					<!-- 	<image src="../../static/images/banner/banner01.jpg" mode="widthFix" style="width: 530rpx"></image> -->
					<!-- <view class="title">{{goodsList.titleOne}}</view> -->
					<view class="goods">

						<view v-if="(categoryName=='全部'?true:item.productCategoryName==categoryName)"  v-for="(item,index) in goodsListNew.pmsProducts" :key="index" >
							<goods-card :price="item.price" @child-event="dialogToggle" :id="item.productId" :oldprice="item.originalPrice" :name="item.productName"></goods-card>
						</view>

						<!-- <view style="height: 20rem;"></view> -->
					</view>
					<!-- <view style="height: 3rem;"></view> -->
				</view>
			</view>

		</view>
		<!-- buy -->
		<view>
			<!-- 确认购买数量 -->
			<uni-popup ref="buyDialog" type="dialog">
				<uni-popup-dialog :type="msgType" cancelText="取消" confirmText="确认" title="选择商品数量"
					@confirm="dialogConfirm" @close="dialogClose">
					<uni-number-box v-model="buyNum" />
				</uni-popup-dialog>
			</uni-popup>
		</view>
		<view>
			<!-- 提示信息弹窗 -->
			<uni-popup ref="message" type="message">
				<uni-popup-message :type="msgType" :message="messageText" :duration="2000"></uni-popup-message>
			</uni-popup>
		</view>
		<!-- bag -->
		<uni-fab ref="fab" horizontal="right" :pattern="pattern" :popMenu="false" @trigger="trigger"
			@fabClick="showDrawer('showLeft')" />
		<view>
			<uni-drawer ref="showLeft" mode="left" :width="320" >
				<view class="close">
					<button @click="closeDrawer('showLeft')"><text class="word-btn-white">关闭</text></button>
				</view>
				<!-- <div style="height: 0.5rem;"></div> -->


				<view v-for="(item,index) in queryOrder.orderProductList" :key="index">
					<bag-item :id="item.productId" :name="item.pmsProduct.productName" @input-change="inputChange"
						@child-event="parentEventHandler" @child-event2="calculation" :price="item.pmsProduct.price"
						:num.sync="item.productNumber"></bag-item>

				</view>
<view class="bagSubmit">
	<view class="bagTotal">
		
					<view style="display: flex; padding-left:2.7rem;">合计：</view>
					<view style="text-align: right; font-size: 1.3rem ;margin-top: 0.2rem;">¥{{totalAmount}}</view>
				</view>
				<view class="" @click="submitBag">提交采买清单</view></view>
				

			</uni-drawer>

		</view>
	</view>
</template>
<script>
	{

	}
	import {
		getCategoryList,
		getBatchListAll
	} from '@/api/system/category.js';

	import {
		listOrder,
		getOrderProductList,
		updateOrderProducts,
		addOrderProducts
	} from '@/api/system/order.js';

	export default {

		onLoad(e) {

			this.qurry.batchId = Number(e.piID)
			// 初始化订单实体(用以第一次提交)
			this.queryOrder.omsOrder.userId = getApp().globalData.userInfo.userId
			this.queryOrder.omsOrder.batchId = e.piID
			this.queryOrder.omsOrder.memberUsername = getApp().globalData.userInfo.nickName
			this.queryOrder.omsOrder.deptId=getApp().globalData.userInfo.dept.deptId
			this.queryOrder.omsOrder.deptName=getApp().globalData.userInfo.dept.deptName
			// 初始化订单查询参数
			this.orderParams.batchId = Number(e.piID);
			this.orderParams.userId = getApp().globalData.userInfo.userId;
			getBatchListAll(this.qurry).then(resq => {
				console.log("1111")
				console.log(resq)
				this.goodsListNew=resq.data[0]
				const listHandle = []
				listHandle[0]={
					name:"全部",
					list:[]
				}
				// this.baseList = resq.data[0].pmsProducts
				resq.data[0].pmsProducts.forEach(item => {
					listHandle[0].list.push(item)
					// 判断数组中是否存在该类别,是否需要创建类别
					const index = listHandle.findIndex(listItem => item.productCategoryName ===
						listItem.name);
					if (index >= 0) {
						listHandle[index].list.push(item)
					} else {
						listHandle.push({
							name: item.productCategoryName,
							list: [item]
						})
					}
				})
				// 初始化类别tab和商品清单
				this.categoryList = listHandle;
				this.goodsList = listHandle[0].list
			})
			this.loadOrder();

		},

		data() {
			return {
				//初始查询参数
				qurry: {
					batchId: 0,
				},
				//订单查询参数
				orderParams: {
					batchId: null,
					userId: null,
				},
				categoryName:"全部",
				goodsListNew:null,
				//订单对象,用以加载查询到的订单详情或者提交订单
				queryOrder: {
					omsOrder: {
						orderId: null,
						orderSn: null,
						batchId: null,
						userId: null,
						memberUsername: null,
						totalAmount: null,
						purchasePrice: null,
						status: null,
						autoConfirmDay: null,
						deleteStatus: null,
						receiveTime: null
					},
					orderProductList: []
				},
				// 总商品清单
				baseList: [],
				// queryOrder: {
				// 	// pageNum: 1,
				// 	// pageSize: 10,
				// 	orderSn: null,
				// 	batchId: null,
				// 	memberUsername: getApp().globalData.userInfo.userName,
				// 	userId: getApp().globalData.userInfo.userId,
				// 	deptId: getApp().globalData.userInfo.dept.deptId,
				// 	deptName: getApp().globalData.userInfo.dept.deptName,
				// 	totalAmount: null,
				// 	purchasePrice: null,
				// 	status: null,
				// 	autoConfirmDay: null,
				// 	deleteStatus: null,
				// 	receiveTime: null,
				// },

				orderList: '',
				// 购买商品相关
				buyNum: 1,
				chooseId: "",
				messageText: "提示框",

				dialogVisible: false,

				bagList: [],
				pattern: {
					color: '#7A7E83',
					backgroundColor: '#fff',
					selectedColor: '#007AFF',
					buttonColor: '#007AFF',
					iconColor: '#fff',
					icon: 'cart',
				},
				btnnum: 0,
				categoryList: '',
				items: ["精选推荐", "华为手机", "荣耀手机", "笔记本", "平板电脑", "智能穿戴"],
				countNum: "0",
				search: "",
				goodsList: {},
				msgType: "info",
				totalAmount: 0,

			};
		},
		onShow() {
			// this.goodsList = this.data[0]
		},
		methods: {
			calculation() {
				console.log('计算')
				let total = 0;
				this.queryOrder.orderProductList.forEach(e => {
					total += e.pmsProduct.price * e.productNumber;
				})
				// console.log(this.orderList.totalAmount)
				this.totalAmount = total;
			},
			loadOrder() {
				console.log("查看订单查询参数")
				console.log(this.queryOrder)
				getOrderProductList(this.orderParams).then(res => {
					//将查询到的订单赋值给订单实体(如果存在)
					console.log("查看订单查询结果和比值")
					console.log(res.data.length > 0)
					if (res.data.length > 0) {
						this.queryOrder = res.data[0]
						//根据订单实体初始化购物车
						if (res.data[0].orderProductList.length > 0) {
							res.data[0].orderProductList.forEach(item => {
									this.bagList.push(item)
								//遍历商品列表,给购物车内的商品赋值
								// const index = this.baseList.findIndex(itemGoodList => itemGoodList
								// 	.productId === item.productId);
								// if (index != -1) {
								// 	const goodsHandle = {
								// 		buyNum: item.productNumber,
								// 		productName: this.baseList[index].productName,
								// 		price: this.baseList[index].price,
								// 		productId:this.baseList[index].productId,
								// 		// batchId:this.baseList[index].batchId,
								// 		// omsOrderProductId:item.omsOrderProductId
								// 	}

								// 	this.bagList.push(goodsHandle)
								// }

							})
						}
					}

					console.log("查看订单查询结果")
					console.log(res)


				})
			},
			// buydialog相关
			dialogToggle(e) {
				console.log("点击了")
				this.chooseId = e,

					this.$refs.buyDialog.open()
			},
			dialogConfirm() {
				console.log("查看添加数量前购物清单")
				console.log(this.bagList)
				//获取当前商品的index
				const index = this.goodsList.findIndex(item => item.productId === this.chooseId);
				// 判断数组中是否包含某个元素
				const contains = this.queryOrder.orderProductList.findIndex(item => item.productId === this.chooseId)
				if (contains !== -1) {
					this.queryOrder.orderProductList[contains].pmsProduct.productNumber += this.buyNum
				} else {
					
					const goodsHandle={
						batchId:this.queryOrder.omsOrder.batchId,
						orderId:this.queryOrder.omsOrder.orderId,
						productId:this.chooseId,
						productNumber:this.buyNum,
						pmsProduct:this.goodsList[index]
					}
					
					this.queryOrder.orderProductList.push(goodsHandle)
				}

				this.messageText = `已将 ${this.buyNum}件商品加入采买清单`
				this.$refs.message.open()
				this.buyNum = 1

			},
			dialogClose() {

				this.buyNum = 1
			},
			submitBag() {

				// const total=0;
				// 遍历采买清单,如果实体里有这个商品就添加数量,如果没有就添加实体
				// this.bagList.forEach(item => {
				// 	// total += item.buyNum * item.price
				// 	const contains = this.queryOrder.orderProductList.findIndex(queryitem => item.productId ===
				// 		queryitem.productId)
				// 	if (contains != -1) {
				// 		this.queryOrder.orderProductList[contains].productNumber = item.buyNum
				// 	} else {
				// 		const bagGoodHandle = {
				// 			productId: item.productId,
				// 			batchId: item.batchId,
				// 			productNumber: item.buyNum,
				// 			orderId:this.queryOrder.omsOrder.orderId
				// 		}
				// 		this.queryOrder.orderProductList.push(bagGoodHandle)
				// 	}

					
					
				// })
				this.queryOrder.omsOrder.totalAmount=this.totalAmount
				// console.log("查看修改参数")
				// console.log(this.queryOrder)
				updateOrderProducts(this.queryOrder).then((res) => {
			this.messageText = `已将采买清单更新至当前批次订单中，可在我的订单中查看`
			this.$refs.message.open()
				})

			},
			//监听子组件商品数量是否减少到了0
			parentEventHandler(e) {
				const id = e
				const index =this.queryOrder.orderProductList.findIndex(queryitem => e ===
					queryitem.productId)
					
				// const finalArr = this.bagList.filter((item) => {
				// 	return id != item.productId
				// })
				this.queryOrder.orderProductList.splice(index,1)
				
				// console.log(finalArr)
				// this.bagList = finalArr
				// this.queryOrder.orderProductList=finalArrOrder
			},

			inputChange(e) {
				this.calculation();
			},
			// 关闭窗口
			closeDrawer(e) {
				this.$refs[e].close()
			},
			// 打开窗口
			showDrawer(e) {
				this.calculation();
				this.$refs[e].open()
			},
			openBag() {
				this.$refs.popup.open('bottom')
			},
			changeMenu(e) {
				// this.calculation();
				this.countNum = e
				this.btnnum = e
				this.categoryName=this.categoryList[e].name
				this.goodsList = this.categoryList[e].list //这里data是获取到的右侧商品数据


			},
			scroll() {},
			getSearch() {}
		}
	}
</script>








<style scoped lang="scss">
	.bagSubmit {
		position: absolute;
		right: 1rem;
		bottom: 1rem;
		background-color: rgba(0, 122, 255, 1);
		padding: 0.5rem;
		color: #fff;

		box-shadow: 4px 4px 2px #888888;
		border-radius: 0.2rem;
	}

	.bagTotal {
		position: absolute;
		right: -3rem;
		width: 5rem;
		height: 5rem;
		bottom: 3rem;
		color: #000000;
		background-color: rgba(255, 255, 255, 1.0);
		padding: 0.5rem;
		display: flex;
		flex-direction: column;
		border-radius: 0.2rem;
	}

	.popup-content {
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.container {
		background-color: #FFFFFF;
		display: flex;
		flex-direction: row;
		height: 100%;
	}

	.main {
		position: fixed;
		display: flex;
		overflow: hidden;
		height: 100%;
	}

	.search-bar {
		width: 100%;
		position: fixed;
		top: 0;
		left: 0;
		color: #777;
		background: #fff;
		box-shadow: 0 2rpx 6rpx rgba(0, 0, 0, 0.07);
		z-index: 3;
		padding: 20rpx 0;

		.arrow {
			width: 20rpx;
			height: 20rpx;
			border-bottom: 2rpx solid #777;
			border-left: 2rpx solid #777;
			transform: rotate(45deg);
			position: absolute;
			left: 30rpx;
			top: 41rpx;
		}

		.search-box {
			display: flex;
			justify-content: center;
			align-items: center;
			height: 60rpx;
			background: #f7f7f7;
			z-index: 999;
			width: 92%;
			border-radius: 50rpx;
			text-align: center;
			margin: auto;

			.search-img {
				width: 32rpx;
				height: 32rpx;
				margin-right: 10rpx;
			}
		}

		.search-hint {
			font-size: 28rpx;
			position: absolute;
			right: 30rpx;
			top: 32rpx;
		}
	}

	.sear-input {
		font-size: 28rpx;
	}

	.navBar {
		padding: 5rpx 32rpx 6rpx 28rpx;
		height: 80rpx;
		display: flex;
		align-items: center;

		&-search {
			margin: 0 auto;
			width: 690rpx;
			height: 58rpx;
			background-color: #F8F9FA;
			border-radius: 30rpx;
			padding-left: 16rpx;
			// margin-right: 32rpx;
			display: flex;
			justify-content: flex-start;
			align-items: center;

			input {
				margin-left: 20rpx;
			}
		}
	}

	.flex-content {
		display: flex;
	}

	.end-title {
		display: flex;
		flex-direction: column;
		width: 180rpx;
		background-color: #F3F5F7;

		view {
			height: 185rpx;
			line-height: 185rpx;
			text-align: center;
			font-size: 26rpx;
			font-weight: bold;
			color: #4E5152;
			border-bottom: 1rpx solid #ECEDEE;
			border-left: 8rpx solid #F3F5F7;
		}

		.btna {
			color: #FF6C5C;
			background-color: #FFFFFF;
			border-left: 8rpx solid #FF6C5C;
		}
	}

	/* .end-title view{flex-grow:1;text-align:center;} */
	.end-cont {
		// width: 550rpx;
		padding-right: 50rpx;


		.title {
			font-size: 30rpx;
			font-weight: bold;
			text-align: center;
			color: #4E5152;
		}

		.goods {
			// font-size: 10rpx;
			width: 100%;
			display: flex;
			flex-direction: column;
			// justify-content: space-around;
			// flex-wrap: wrap;
			height: 90vh;
			overflow-y: auto;

		}

		image {
			margin: 20rpx 0 60rpx 20rpx;
		}
	}

	.dis {
		display: block;
	}
</style>